package top.zhangjianyong.blog.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.zhangjianyong.blog.cache.VCodeCache;
import top.zhangjianyong.blog.component.MailSend;
import top.zhangjianyong.blog.enums.RespCode;
import top.zhangjianyong.blog.entity.po.User;
import top.zhangjianyong.blog.params.common.SendVCodeParam;
import top.zhangjianyong.blog.response.ApiResponse;
import top.zhangjianyong.blog.service.CommonService;
import top.zhangjianyong.blog.service.UserService;

/**
 * 通用Service
 *
 * @author zhangjianyong
 * @since 2024/7/19 下午7:40
 */
@Slf4j
@Service
public class CommonServiceImpl implements CommonService {

  private final UserService userService;
  private final MailSend mailSend;

  public CommonServiceImpl(UserService userService, MailSend mailSend) {
    this.userService = userService;
    this.mailSend = mailSend;
  }

  @Override
  public ApiResponse sendVCode(SendVCodeParam param) {

    User user = userService.queryByUsername(param.username());
    if (null == user) {
      return ApiResponse.fail(RespCode.USER_NOT_FUND);
    }
    String email = user.getEmail();

    // 生成验证码
    int vCode = VCodeCache.generateVCode(email);
    mailSend.sendAsync(email, "验证码", "" + vCode);
    return ApiResponse.success();
  }
}
